﻿using NetMQ;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace _0MQClient
{
    class Program
    {
        static void Main(string[] args)
        {
            NetMQContext context = NetMQContext.Create();
            Client(context);
            Console.ReadKey();
        }

        static void Client(NetMQContext context)
        {
            using (NetMQSocket clientSocket = context.CreateRequestSocket())
            {
                clientSocket.Connect("tcp://127.0.0.1:5555");

                Dictionary<string, object> dic = new Dictionary<string, object>();
                dic.Add("a", 1);
                dic.Add("b", 2);

                Message msg = new Message()
                {
                    Id = 0,
                    FunName = "Calc",
                    Params = dic,
                    Result = ""
                };

                byte[] buffer = Object2Bytes(msg);
                clientSocket.SendFrame(buffer);
                string answer = clientSocket.ReceiveFrameString();
                Console.WriteLine("Answer from server: {0}", answer);
            }
        }
        /// <summary>  
        /// 将对象转换为byte数组  
        /// </summary>  
        /// <param name="obj">被转换对象</param>  
        /// <returns>转换后byte数组</returns>  
        public static byte[] Object2Bytes(object obj)
        {
            byte[] buff;
            using (MemoryStream ms = new MemoryStream())
            {
                IFormatter iFormatter = new BinaryFormatter();
                iFormatter.Serialize(ms, obj);
                buff = ms.GetBuffer();
            }
            return buff;
        }

        /// <summary>  
        /// 将byte数组转换成对象  
        /// </summary>  
        /// <param name="buff">被转换byte数组</param>  
        /// <returns>转换完成后的对象</returns>  
        public static object Bytes2Object(byte[] buff)
        {
            object obj;
            using (MemoryStream ms = new MemoryStream(buff))
            {
                IFormatter iFormatter = new BinaryFormatter();
                obj = iFormatter.Deserialize(ms);
            }
            return obj;
        }

    }

    [Serializable]
    public class Message
    {
        public int Id { set; get; }

        public string FunName { set; get; }

        public Dictionary<string, object> Params { set; get; }

        public string Result { set; get; }
    }
}
